package com.jstyle.jclife.activity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.HistoryDateAdapter;
import com.jstyle.jclife.adapter.SportDataDayAdapter;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.StepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclife.fragment.ExerciseFragment;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.StepData;
import com.jstyle.jclife.model.StepDetailData;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.Utils;
import com.jstyle.jclife.view.ActivityHistoryCircleProgress;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.view.ColumnChartView;

/**
 * 步数日界面
 */
public class ActivityHistoryActivity extends BaseActivity {

    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.iv_activity_history_left)
    ImageView ivActivityHistoryLeft;

    @BindView(R.id.iv_activity_history_right)
    ImageView ivActivityHistoryRight;
    @BindView(R.id.RecyclerView_data_day)
    RecyclerView RecyclerViewDataDay;
    @BindView(R.id.ColumnChartView_day)
    ColumnChartView ColumnChartViewDay;
    @BindView(R.id.ActivityHistoryCircleProgress)
    ActivityHistoryCircleProgress ActivityHistoryCircleProgress;
    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.scrollView_step)
    ScrollView scrollViewStep;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.ll_child)
    LinearLayout llChild;

    private HistoryDateAdapter historyDateAdapter;
    private SportDataDayAdapter sportDataDayAdapter;

    private static final String TAG = "ActivityHistoryActivity";
    private String queryDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_day);
        ButterKnife.bind(this);

        init();
        initData();
    }

    private void initData() {
        ScreenUtils.setTitleTypeface(btGoalBack);

        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        ivActivityHistoryRight.setEnabled(!queryDate.equals(nowDate));
        btSleepWeekDate.setText(DateUtil.getShowDay(this, queryDate));
        StepData stepData = StepDataDaoManager.queryData(queryDate);

        List<StepDetailData> list = StepDetailDataDaoManager.queryData(queryDate);
        List<HeartData> heartDataList = HeartDataDaoManager.queryDayData(queryDate);
        int[] minSteps = new int[1440];//24*60分钟
        int maxStep = 0;

        for (StepDetailData stepDetailData : list) {
            String date = stepDetailData.getDate();
            String steps = stepDetailData.getMinterStep();
            String[] stepString = steps.split(" ");//10分钟的步数
            int startCount = DateUtil.get1MIndex(date, queryDate + " 00:00:00");
            for (int i = 0; i < stepString.length; i++) {
                int endCount = startCount + i;
                if (endCount > 1439) break;//夜晚跨天
                minSteps[endCount] = Integer.valueOf(stepString[i]);
                maxStep = Math.max(maxStep, Integer.valueOf(stepString[i]));
            }
        }
        initChartView(minSteps, maxStep);
        String[] datas = new String[]{"0", "0", "0", "00:00", "00:00"};
        String step = "0";
        String goal = "0";
        int totalHr = 0;
        int count = 0;
        for (HeartData heartData : heartDataList) {
            int hr = heartData.getHeart();
            if (hr != 0) {
                totalHr += hr;
                count++;
            }
        }
        int avgHr = count == 0 ? 0 : totalHr / count;
        if (stepData != null) {
            datas[0] = stepData.getCal();
            datas[1] = stepData.getDistance();
            datas[2] = String.valueOf(avgHr);
            datas[3] = DateUtil.getActivityTime(Integer.valueOf(stepData.getTime()));
            datas[4] = DateUtil.getActivityTime(Integer.valueOf(stepData.getExerciseTime()));
            step = stepData.getStep();
            goal = stepData.getGoal();
            Log.i(TAG, "initData: " + stepData.getGoal());
        }
        ActivityHistoryCircleProgress.update(Integer.valueOf(step), Integer.valueOf(goal));
        sportDataDayAdapter.setDatas(datas);
        //  Log.i(TAG, "initData: " + stepData.getDate() + " " + stepData.getStepStatus());

    }

    private void init() {
        queryDate = DateUtil.getDefaultFormatTime(new Date());
        String queryDateNow=getIntent().getStringExtra(ExerciseFragment.KEY_QUERYDATE);
        queryDate=TextUtils.isEmpty(queryDateNow)?queryDate:queryDateNow.substring(2);
        List<String> list = new ArrayList<>();
        list.add(getString(R.string.cal));
        list.add(getString(R.string.distance));
        list.add(getString(R.string.avg_historyhr));
        list.add(getString(R.string.Active_Minutes));
        list.add(getString(R.string.Exercise_Minutes));

        FlexboxLayoutManager layoutManagerData = new FlexboxLayoutManager(this);
        sportDataDayAdapter = new SportDataDayAdapter(list);

        RecyclerViewDataDay.setAdapter(sportDataDayAdapter);
        RecyclerViewDataDay.setLayoutManager(layoutManagerData);


    }

    private void initChartView(int[] stepData, int maxStep) {
        int max = 0;
        for (int i = 0; i < 24; i++) {
            int stepTotal = 0;
            int start = i * 60;
            for (int j = 0; j < 60; j++) {
                int step = stepData[j + start];
                stepTotal += step;
            }
            max = Math.max(max, stepTotal);
        }
        Typeface mFace = Typeface.createFromAsset(getAssets(), "Brandon_reg.otf");

        ChartDataUtil.initDataChartView(ColumnChartViewDay, -0.5f, max * 1.2f, 23.5f, 0);
        ColumnChartViewDay.setColumnChartData(ChartDataUtil.getStepDayColumnChart(stepData, max, mFace));
    }

    private float getChartMax(float max) {
        int maxData = 0;
        String distanceStep = String.valueOf((int) max);
        int lengthStep = distanceStep.length();
        if (lengthStep < 3) lengthStep = 3;
        double countStep = Math.pow(10, lengthStep - 1);
        int resultStep = (int) (max / countStep);
        if (resultStep < 5) {
            maxData = (int) (5 * countStep);
        } else {
            maxData = (int) (10 * countStep);
        }
        return maxData;
    }

    @OnClick({R.id.iv_back, R.id.iv_share, R.id.iv_activity_history_right, R.id.iv_activity_history_left})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
//                LayoutInflater layoutInflater=LayoutInflater.from(this);
//                View viewBottom=layoutInflater.inflate(R.layout.layout_share_bottom,llChild,false);
//                llChild.addView(viewBottom);
                ScreenUtils.shareFile(this, llRoot);
                break;
            case R.id.iv_activity_history_right:
//                showWeek = DateUtil.getWeekString(showWeek[6], DateUtil.nextWeek);
//                historyDateAdapter.setData(showWeek);
                queryDate = DateUtil.getTomorrowDateString(queryDate);
                initData();
//                changeData(position);
                break;
            case R.id.iv_activity_history_left:
                queryDate = DateUtil.getYesterdayDateString(queryDate);
                initData();
//                showWeek = DateUtil.getWeekString(showWeek[0], DateUtil.lastWeek);
//                historyDateAdapter.setData(showWeek);
//               changeData(position);
                break;
        }
    }


}
